<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <title>login</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="loginContent">
    <h1>请你摇一摇</h1>
    <strong>    <!-- 摇一摇的声音 -->
        <audio src="../static/shake/music/red-01.mp3" preload="preload" id="shakingAudio"></audio>
        <!-- 摇到红包的声音 -->
        <audio src="../static/shake/music/red-02.mp3" preload="preload" id="shakingResult"></audio>
    </strong>
    <p id="numberCount"></p>
</div>
<script type="text/javascript" th:inline="JavaScript">

    var SHAKE_THRESHOLD = 1800;  //定义触发动作的阈值
    var last_update = 0;         //上一次触发的时间
    var x = y = z = last_x = last_y = last_z = 0;//x,y,z当前加速度,last_z,last_x,last_y上次加速度
    var num = 0;
    var numMax = 3;

    listenPhoneShake();

    function listenPhoneShake() {
        if (window.DeviceMotionEvent) {
            window.addEventListener('devicemotion', deviceMotionHandler,false);
            console.log("addEventListener devicemotion");
        } else {
            alert('抱歉，你的手机配置实在有些过不去，考虑换个新的再来试试吧');
        }
    }


    function deviceMotionHandler(eventData) {
        var acceleration = eventData.accelerationIncludingGravity;
        var curTime = new Date().getTime();

        if ((curTime - last_update) > 100) {
            var diffTime = curTime - last_update;
            last_update = curTime;
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

            if (speed > SHAKE_THRESHOLD) {
                handelShakingMotion();
            }
            last_x = x;
            last_y = y;
            last_z = z;
        }
    }


    function handelShakingMotion() {
        num++;
        // 添加摇一摇的声音
        $('#shakingAudio').trigger('play');
        document.getElementById("numberCount").innerHTML = num;
        if (num == numMax) {
            num = 0;
            // 关闭摇一摇的接口
            window.removeEventListener("devicemotion", deviceMotionHandler);
            // 添加摇到红包的声音
            $('#shakingResult').trigger('play');
            // 摇一摇结束之后，请求抢红包接口
            //drawRedbag(openid);
        }
    }
    
    function drawRedbag() {
        
    }
</script>
</body>
</html>